package cn.jinjimi.app.reader;

import android.content.Context;

import cn.jinjimi.app.interfaces.IRVGridHeaderable;
import cn.jinjimi.app.poster.bean.PosterInfo;
import cn.jinjimi.app.reader.bean.JinjuViewData;
import cn.jinjimi.app.reader.bean.PosterInfos;
import cn.jinjimi.app.main.widget.CommonRV.BaseHolder;
import cn.jinjimi.app.main.widget.CommonRV.BaseRvAdapter;
import cn.jinjimi.app.main.widget.CommonRV.HolderType;
import cn.jinjimi.app.main.widget.CommonRV.IActionListener;
import cn.jinjimi.app.main.widget.CommonRV.IViewData;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Created by lforxeverc on 2017/4/14.
 */

public class ReaderAdapter<D extends IViewData> extends BaseRvAdapter<D> implements IRVGridHeaderable {
    public ReaderAdapter(Context mContext, IActionListener l) {
        super(mContext, l);
    }

    @Override
    public boolean isHeader(int position) {
        if (position >= getItemCount() || getItemCount() == 0) return true;
        int viewType = getItem(position).getViewType();
        return viewType == ReaderHolderFactory.TYPE_ARTICLE ||
                viewType == ReaderHolderFactory.TYPE_SEARCH ||
                viewType == HolderType.TYPE_NO_MORE;
    }

    @Override
    public BaseHolder onCreateViewHolder(int viewType) {
        return ReaderHolderFactory.create(getContext(), viewType);
    }


    public PosterInfos getPostInfosAt(int position) {
        PosterInfos info = null;
        List<PosterInfo> infos = new ArrayList<>();
        List<D> data = getItems();
        int p = 0;
        if (data != null && !data.isEmpty() && data.size() > position) {
            //往前获取金句类型的数据
            for (int i = position; i >= 0; i--) {
                D d = getItem(i);
                if (d.getViewType() == ReaderHolderFactory.TYPE_JINJU) {
                    JinjuViewData jinju = (JinjuViewData) d;
                    PosterInfo info1 = new PosterInfo(jinju.getCoverUrl(), Integer.parseInt(jinju.getId()));
                    infos.add(info1);
                    p++;
                } else {
                    break;
                }
            }
            Collections.reverse(infos);
            //往后遍历
            for (int i = position + 1; i < getItemCount(); i++) {
                D d = getItem(i);
                if (d.getViewType() == ReaderHolderFactory.TYPE_JINJU) {
                    JinjuViewData jinju = (JinjuViewData) d;
                    PosterInfo info1 = new PosterInfo(jinju.getCoverUrl(), Integer.parseInt(jinju.getId()));
                    infos.add(info1);
                } else {
                    break;
                }
            }

        }
        info = new PosterInfos(infos, p - 1);
        return info;
    }
}
